<?php
/**
 * SemesterSubject Model
 *
 * Utilizes the Data Mapper pattern to persist data. Represents a single
 * semester_subject entry
 *
 * @version $Id: SemesterSubject.php 128 2010-06-29 03:44:03Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Semester_Model_SemesterSubjectMapper
 * @package semester
 * @subpackage Model
 */
class Semester_Model_SemesterSubject extends Semester_Model_Doctrine_BaseSemesterSubject
{
    /**
     * 全學期打一次成績
     * @var integer
     */
    const SCORE_MODE_WHOLE_SEMESTER = 0 ;


    const SCORE_MODE_SCORED = 'Y';
    /**
     * 每階段輸入成績
     * @var integer
     */
    const SCORE_MODE_STAGE  = 1;

    const CLASS_ALL  = 255;

    /**
     *
     * @param integer $year 學年
     * @param integer $semester 學期
     * @param integer $grade 年級
     * @param integer $classSn 班級
     * @param integer|NULL $scored_mode  全學期輸入或階段輸入
     * @param string|NULL $scored 計分否
     */
    public function getSubject($year, $semester, $grade, $classSn='',$scored_mode=null,$scored=null)
    {
        $q = $this->getTable()->createQuery('a')
        ->select('a.*, b.name AS name, b.scope AS scope, b.special AS special, b.scope_rank AS  scope_rank, b.rank AS rank')
        ->leftJoin('a.Semester_Model_SemesterCourse b')
        ->where('a.year=?', $year)
        ->andWhere('a.semester=?', $semester)
        ->andWhere('a.grade=?', $grade)
        ->andWhere("a.enable IS NULL OR a.enable='Y'");
        if ($scored_mode !== NULL) {
            $q->addWhere('a.scored_mode=?',$scored_mode);
        }
        if ($scored !== NULL)
          $q->addWhere('a.scored=?',$scored);

        if ($classSn !=  self::CLASS_ALL) {
            if ($classSn)
            $q->andWhere('a.class_sn=?',$classSn);
            else {
                $q->groupby('a.subject_sn');
            }
        }
        $q->orderby('b.scope_rank, b.rank');

        $res = $q->fetchArray();
        $arr = array();
        foreach($res as $val) {
            $scopeArr = explode("-",$val['scope']);
            if (count($scopeArr)>1) {
                if ($classSn ==  self::CLASS_ALL)
                $arr[$val['class_sn']][$scopeArr[0]][] = $val;
                else
                $arr[$scopeArr[0]][] = $val;
            }
            else {
                if ($classSn ==  self::CLASS_ALL)
                $arr[$val['class_sn']][$val['scope']][] = $val;
                else
                $arr[$val['scope']][] = $val;
            }
        }
        return $arr;
    }

}
